package com.github.shiqiyue.myadmin.config.security;

import com.github.shiqiyue.myadmin.config.security.authentication.provider.AdminAuthenticationProvider;
import com.github.shiqiyue.myadmin.service.system.rolemenu.RoleMenuService;
import com.github.shiqiyue.myadmin.service.system.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

/***
 * web安全配置
 *
 * @author wwy
 *
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    @Qualifier("adminPasswordEncoder")
    private PasswordEncoder passwordEncoder;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        // 定义认证信息提供者
        AdminAuthenticationProvider authenticationProvider = new AdminAuthenticationProvider(userService,
                passwordEncoder);
        authenticationProvider.setRoleMenuService(roleMenuService);
        auth.authenticationProvider(authenticationProvider).eraseCredentials(true);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 配置表单登录
        http.formLogin().loginPage("/admin/login").loginProcessingUrl("/admin/login").defaultSuccessUrl("/admin/main");
        // 配置登出
        http.logout().logoutUrl("/admin/logout").logoutSuccessUrl("/admin/login");
        // 禁用csrf
        http.csrf().disable();
        // 允许iframe
        http.headers().frameOptions().sameOrigin();
        // 配置 rememberme功能
        http.rememberMe().rememberMeParameter("rememberMe").alwaysRemember(false).userDetailsService(userService)
                .key("fsafasfafafa-fafafa");
        http.authorizeRequests().antMatchers("/admin/login").permitAll();
        http.authorizeRequests().antMatchers("/admin/**").authenticated();
        http.authorizeRequests().antMatchers("/**").permitAll();

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

}
